import type {HeadingCache} from "obsidian";

export class GetCascadeHeader {
    public static getUpLevelHeadingSuggestions(headings: HeadingCache[] | undefined) {
        const upLevelHeadingSuggestions = new Map();
        if (headings === undefined) {
            return upLevelHeadingSuggestions;
        }

        const upLevelHeadingsMap = this.getUpLevelHeadingRecursively(headings);
        // console.log(upLevelHeadingsMap);
        upLevelHeadingsMap.forEach((headingCacheArray, keyHeading) => {
            if (keyHeading != undefined) {
                const reversedArray = headingCacheArray.reverse();
                const upLevelHeadingsText: string[] = reversedArray.map(v => "#".repeat(v.level) + ` ${v.heading}`);
                upLevelHeadingSuggestions.set("#".repeat(keyHeading.level) + ` ${keyHeading.heading}`, upLevelHeadingsText);
            }
        });
        return upLevelHeadingSuggestions;
    }

    public static getUpLevelHeadingRecursively(cachedHeadings: HeadingCache[]) : Map<HeadingCache, HeadingCache[]>{
        const upLevelHeadingsArray = cachedHeadings.map((_item, i) => {
            const chain: HeadingCache[] = [];
            this.getUpLevelHeading(i, cachedHeadings, chain);
            return chain;
        });

        const upLevelHeadingsMap = new Map();
        for(const heading of upLevelHeadingsArray){
            upLevelHeadingsMap.set(heading[0], heading.slice(1));
        }
        return upLevelHeadingsMap;
    }

    public static getUpLevelHeading(headingIndex: number, headingCandidates: HeadingCache[], headingChain: HeadingCache[]) {
        const currentHeading = headingCandidates[headingIndex];
        const level = currentHeading.level;
        if (level <= 2) {
            headingChain.push(currentHeading);
            return;
        }
        const upLevel = level - 1;
        for (let i = headingIndex; i--; i>= 0)
        {
            if (headingCandidates[i].level <= upLevel){ // 找到上一级heading
                headingChain.push(currentHeading);
                this.getUpLevelHeading(i, headingCandidates, headingChain);
                break;
            }
        }
    }
}
